/**
 * 爬取拿到封面图和视频的数据
 */

const puppeteer = require('puppeteer');

const base = 'https://movie.douban.com/subject/'
const doubanId = '26949264'
const videoBase = `https://movie.douban.com/trailer/231606`

const sleep = time => new Promise(resolve => {
    setTimeout(resolve, time)
})

;
(async () => {
    console.log('start visit the target page')

    const browser = await puppeteer.launch({
        args: ['--no-sandbox'],
        dumpio: false,
    })

    //  创建连接
    const page = await browser.newPage()
    await page.goto(base+doubanId, {
        waitUntil: 'networkidle2'
    })

    await sleep(1000)

    //  爬取封面的数据
    const result = await page.evaluate(() => {
        var $ = window.$;
        var it = $('.related-pic-video'); //  拿到视频dom节点
        
        if(it && it.length>0){
            var link = it.attr('href');  //  预告片的视频地址
            var cover = it.css('backgroundImage').slice(5,it.css('backgroundImage').length-2);  //  预告片的封面地址
            return {
                link,
                cover
            }
        }

        return {};
    })

    let video;

    //  如果有预告片的视频地址继续爬预告片视频
    if(result.link){
        await page.goto(result.link,{
            waitUntil:'networkidle2'
        })
        await sleep(2000)

        video = await page.evaluate(()=>{
            var $ = window.$;
            var it = $('source');

            if(it && it.length>0){
                return it.attr('src')
            }
            return ''
        })
    }

    //  发送需要的总数据
    const data = {
        video,
        doubanId,
        cover:result.cover
    }


    //  关闭浏览器
    browser.close();
    // console.log(result)
    process.send({
        data
    })
    process.exit(0)
})()